package examples;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.joda.time.DateTime;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.lxit.cms.entity.assist.CmsGuestbook;
import com.lxitedu.tool.SMSTool;

public class ExampleBusinessObject implements ServletContextAware {
	public void doIt() {
		System.out.println("ExampleBusinessObject.doIt()" + new Date());
		sendEms();
	}

	private void sendEms() {
		System.out.println("ExampleBusinessObject.sendems()");
		WebApplicationContext webApplicationContext = WebApplicationContextUtils
				.getRequiredWebApplicationContext(servletContext);
		SessionFactory sessionFactory = (SessionFactory) webApplicationContext
				.getBean("sessionFactory");
		Session session = sessionFactory.openSession();
		Query query = session
				.createQuery("from CmsGuestbook where (replayTime is null) and (assignDate is not null)");
		List list = query.list();
		for (Object cmsGuestBook : list) {
			CmsGuestbook cmsGuestbook = (CmsGuestbook) cmsGuestBook;

			DateTime assignTime = new DateTime(cmsGuestbook.getAssignDate());
			cmsGuestbook.setLimitDate(3);
			Integer limitDate = cmsGuestbook.getLimitDate();

			DateTime beforeTime = assignTime.plusDays(limitDate - 1);
			DateTime planTime = assignTime.plusDays(limitDate);

			DateTime now = new DateTime(new Date());
			if (beforeTime.compareTo(now) < 0 && planTime.compareTo(now) > 0) {
				sendDetailMessage(cmsGuestbook, "你有群众留言明天就要过期: ");
			} else if (planTime.compareTo(now) < 0) {
				sendDetailMessage(cmsGuestbook, "你有群众留言今天就要过期了: ");
			}

		}
		session.close();
	}

	private void sendDetailMessage(CmsGuestbook cmsGuestbook, String preMessage) {
		if (cmsGuestbook.getAdmin().getMoblie() != null) {
				SMSTool.sendMessage(cmsGuestbook.getAdmin().getMoblie(),
						preMessage + cmsGuestbook.getContent());
		}
	}

	ServletContext servletContext;

	@Override
	public void setServletContext(ServletContext arg0) {
		servletContext = arg0;
	}
}